package cn.wzx.core.translation.aop.service;

import cn.wzx.core.translation.aop.annotation.TransData;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;

/**
 * @author wzx
 * @date 2024/11/11 10:26
 * @description: Database
 */
@Service
public class DatabaseTranslator implements Translator{

    @Autowired
    private BaseMapper<Object> baseMapper;

    @Override
    public Object translate(String targetSource,String SqlField , String redisSource , String targetField,String translateField ) {
        // 该方法目前并不实际执行翻译，在 AOP 切面中实现
        return null;
    }

    // 辅助方法：在对象中执行翻译
    public void performTranslation(Object object) throws IllegalAccessException, NoSuchFieldException {
        // 遍历所有字段
        for (Field field : object.getClass().getDeclaredFields()) {
            // 检查字段是否有 TransData 注解
            TransData transData = field.getAnnotation(TransData.class);
            if (transData != null && "mysql".equals(transData.type())) {
                // 如果字段带有 TransData 注解且数据源为 mysql
                field.setAccessible(true);

                // 获取注解信息
                Class<?> entityClass = transData.targetClass();
                String sqlField = transData.SqlField();
                String translateField = transData.translateField();
                Object sqlFieldValue = field.get(object); // 被翻译字段的值

                // 查询数据库，构建 QueryWrapper 条件
                QueryWrapper<Object> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq(sqlField, sqlFieldValue);

                // 从数据库中获取翻译后的数据
                Object result = baseMapper.selectOne(queryWrapper);

                // 设置翻译后的字段值
                if (result != null) {
                    Field translateFieldInEntity = entityClass.getDeclaredField(translateField);
                    translateFieldInEntity.setAccessible(true);
                    Object translatedValue = translateFieldInEntity.get(result);
                    field.set(object, translatedValue);
                }
            }
        }
    }
}
